<?php
namespace app\index\controller;

use think\Request;
use app\index\model\User;
use app\index\model\Sms;
use app\index\validate\User as UserValidate;

class Password extends Base
{
    public function index()
    {
        // 跳转到注册页面
        $this->redirect('password/reset');
    }

    public function create()
    {
        return $this->fetch('create');
    }

    public function ajax_check_present(Request $request)
    {
        if(!$request->isAjax()){
            $this->redirect('login/create');
        }

        $mobile = $request->post('mobile');
        $userModel = new User();
        if($userModel->where('mobile', $mobile)->count()){
            echo("true");
        }else{
            echo("false");
        }
    }

    public function verify_code(Request $request)
    {
        if(!$request->isAjax()){
            $this->redirect('login/create');
        }

        $mobile = $request->post('mobile');
        $sms = new Sms();
        $send_result = $sms->sendCode($mobile);
        return json($send_result);
    }

    public function ajax_valid_code(Request $request)
    {
        if(!$request->isAjax()){
            $this->redirect('login/create');
        }

        $is_valid = false;

        $validate = new UserValidate();
        $param = $request->post();
        if(isset($param['sms_code'])){
            $sms_code = $param['sms_code'];
            $is_valid = $validate->checkCode($sms_code, '', $param);
        }

        if($is_valid === true){
            echo("true");
        }else{
            echo("false");
        }
    }

    public function save(Request $request)
    {
        if(!$request->isAjax()){
            $this->redirect('register/create');
        }

        $param = $request->post();
        $userModel = new User();
        $result = $userModel->resetPassword($param);
        if($result->status){
            $this->success($result->message, url('login/create'));
        }else{
            $this->error($result->message);
        }
    }
}
